package jmind.core.manager;

import jmind.core.jdbc.DataSourceFactory;
import org.apache.commons.dbcp.BasicDataSource;

import javax.sql.DataSource;
import java.util.concurrent.FutureTask;

/**
 * DataSource 管理，避免多个项目构建重复DataSource
 * @author xieweibo
 *
 */
public class DataSourceManager extends AbstractManager<DataSource> {

    private static volatile DataSourceManager manager;

    public static DataSourceManager getInstance() {
        if (manager == null) {
            synchronized (DataSourceManager.class) {
                if (manager == null) {
                    manager = new DataSourceManager();
                }
            }
        }
        return manager;
    }

    @Override
    public DataSource create(String name) {
        return DataSourceFactory.createFactory(getProperties().getProperty("jdbc." + name + ".datasource")).getSource(name,getProperties());
    }

    @Override
    public void releaseResource() {
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                for (FutureTask<DataSource> source : RESOURCES.values()) {
                    try {
                        BasicDataSource ds = (BasicDataSource) source.get();
                        ds.close();
                    } catch (Exception e) {
                        logger.error("DataSourceManager releaseResource error!", e);
                    }
                }
                logger.debug("releaseResource {}", getClass().getName());
            }
        });
    }

}
